const Validator = require('../../../utils/validator')
Parse.Cloud.define('addAdmin', async (req, res) => {
  const currentUser = req.user
  if (!currentUser) {
    return res.error('请先登录')
  }

  const permission = { sessionToken: currentUser.getSessionToken() }
  const {username, password, roles} = req.params
  // 数据校验
  const rules = {
    username: [{type: 'string', required: true, message: '请提供用户名'}],
    password: [{type: 'string', required: true, message: '请提供密码'}],
    roles: [{type: 'array', required: true, message: '请提供所属角色'}]
  }
  const validator = new Validator(rules)
  const errors = validator.validate({username, password, roles})
  if (errors[0]) {
    return res.error(errors[0].message)
  }

  try {
    // 检测角色是否正确
    const currentRoles = await new Parse.Query(Parse.Role).containedIn('objectId', roles).find(permission)
    if (currentRoles.length !== roles.length) {
      return res.error('角色不正确')
    }
    // 用户注册
    const user = new Parse.User()
    user.set('username', username)
    user.set('password', password)
    const current = await user.signUp()
    // 设置角色
    Parse.Object.saveAll(currentRoles.map(item => {
      item.getUsers().add(current)
      return item
    }), permission)
    res.success('ok')
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})

